package thread;


import java.util.Scanner;

/**
 * 多线程练习
 */
public class ThreadExercise01 {

    public static void main(String[] args) {

        /*
            1)在main方法中启动两个线程
            2)第1个线程循环随机打印100以内的整数
            3)直到第2个线程从键盘读取了"Q"命令
         */
        TE te = new TE();
        TE2 te2 = new TE2(te);
        te.start();
        te2.start();
    }
}

class TE extends Thread {

    private boolean flag = true;

    @Override
    public void run() {

        while (flag) {
            System.out.println((int)(Math.random() * 100 + 1));
            //休眠
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public void setFlag(boolean flag) {
        this.flag = flag;
    }
}

class TE2 extends Thread {

    private TE te;

    private Scanner scanner = new Scanner(System.in);

    public TE2(TE te) {
        this.te = te;
    }

    public void setTe(TE te) {
        this.te = te;
    }

    @Override
    public void run() {
        while (true) {
            //接受到用户的输入
            System.out.println("请输入指令(Q)退出：");
            char key = scanner.next().toUpperCase().charAt(0);
            if (key == 'Q') {
                //以通知的方式结束TE线程
                te.setFlag(false);
                System.out.println("TE2线程退出...");
                break;
            }
        }
    }
}